package com.rpc.core.holder.transmit;

import com.rpc.core.remoting.Client;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class RequestSync {

    private Response response;

    private Request request;

    public Request getRequest() {
        return request;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    private CountDownLatch downLatch = new CountDownLatch(1);
    Client client;

    public RequestSync(Client client) {
        this.client = client;
    }

    public Response send(Request request, Long timeout, TimeUnit unit) {

        this.request = request;
        client.sendSync(this);
        try {
            downLatch.await(timeout, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        if(response==null){
            client.remove(request.getId());
        }
        return response;
    }

    public void down(Response response) {
        this.response = response;
        downLatch.countDown();
    }



}
